// 根据经纬度获取地理位置
export const nglatToAddress = (lnglat, call) => {
  // 根据经纬度获取详细地址
  if (window.AMap) {
    // 读取详细地址
    try {
      const geocoder = new window.AMap.Geocoder({ city: "全国" });
      geocoder.getAddress(lnglat, function(status, result) {
        call && call(result);
      });
    } catch (e) {
      call && call();
    }
  } else {
    call && call();
  }
};
// 根据经纬度获取地理位置
export const addressToDetail = (address, call) => {
  // 根据经纬度获取详细地址
  if (window.AMap) {
    // 读取详细地址
    try {
      const geocoder = new window.AMap.Geocoder({ city: "全国" });
      geocoder.getLocation(address, function(status, result) {
        call && call(result);
      });
    } catch (e) {
      call && call();
    }
  } else {
    call && call();
  }
};
// 获取我都位置经纬度
export const getMineLnglat = call => {
  // 获取当前地址经纬度
  if (window.GETMINEADDRESS) {
    try {
      window.GETMINEADDRESS.getCurrentPosition(function(status, result) {
        call && call(result);
      });
    } catch (e) {
      call && call();
    }
  } else {
    call && call();
  }
};
// 组合我的获取最终的地址
export const getAddress = call => {
  // 获取我的位置的经纬度
  getMineLnglat(result => {
    const rs = result || {};
    let lnglat = rs.position || {};
    // 根据经纬度获取详细地址
    nglatToAddress(lnglat, result1 => {
      const citys = addressInfo(result1, lnglat);
      call && call(citys, result1);
    });
  });
};

// 搜索poi数据
export const getPoiList = (keywords, citys, call) => {
  if (window.AMap) {
    const autoOptions = {
      city: citys.code || "全国",
      citylimit: true, // 是否强制限制在设置的城市内搜索,默认值为：false true：强制限制设定城市，false：不强制限制设定城市
      datatype: "all"
    };
    try {
      const placeSearch = new window.AMap.PlaceSearch(autoOptions);
      placeSearch.search(keywords, function(status, result) {
        call && call(result);
      });
    } catch (e) {
      call && call({});
    }
  } else {
    call && call({});
  }
};

// 根据getMineLnglat获取到的信息来获取详细的城市信息
export const addressInfo = (detail, lnglat) => {
  const dt = detail || {};
  const ll = lnglat || dt.location || {};
  const all = dt.regeocode || dt || {};
  const item = all.addressComponent || {};
  let citys = {
    cityCode: item.citycode || "", // 城市编号
    address: all.formattedAddress || "", // 详细地址
    cityName: item.city || item.province || "", // 城市名称
    flat: ll.lat || "", // 地址纬度
    flng: ll.lng || "" // 地址精度
  };
  return citys;
};
let drivingMap = null;
export const drivingClear = () => {
  drivingMap && drivingMap.clear && drivingMap.clear();
  drivingMap && drivingMap.clearAvoidRoad && drivingMap.clearAvoidRoad();
  drivingMap &&
    drivingMap.clearAvoidPolygons &&
    drivingMap.clearAvoidPolygons();
};
// 构建绘制地图线路
/**
 * 绘制路线
 * @param form 出发地
 * @param to 目的地
 * @param TheRoad 是否显示路况
 */
export const driving = (form, to, TheRoad) => {
  //构造路线导航类
  drivingClear();
  if (TheRoad) {
    drivingMap = new AMap.Driving({
      showTraffic:false,
      map: window.MAPINSTANCE
    });
  }else {
    drivingMap = new AMap.Driving({});
  }
  // 根据起终点经纬度规划驾车导航路线
  if (TheRoad) {
    drivingMap.search(
      new window.AMap.LngLat(form.flng, form.flat),
      new window.AMap.LngLat(to.flng, to.flat),
      function(status, result) {
        // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
        if (status === "complete") {
          console.log("绘制驾车路线完成");
        } else {
          console.log("获取驾车数据失败：" + result);
        }
      }
    );
    return;
  }
  drivingMap.search(
    new window.AMap.LngLat(form.flng, form.flat),
    new window.AMap.LngLat(to.flng, to.flat),
    function(status, result) {
      // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
      if (status === "complete") {
        if (result.routes && result.routes.length) {
          // 绘制第一条路线，也可以按需求绘制其它几条路线
          drawRoute(result.routes[0]);
          console.log("绘制驾车路线完成");
        }
      } else {
        console.warn("获取驾车数据失败：" + result);
      }
    }
  );
};

function drawRoute(route) {
  let path = parseRouteToPath(route);

  let startMarker = new window.AMap.Marker({
    position: path[0],
    icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png",
    map: window.MAPINSTANCE
  });

  let endMarker = new window.AMap.Marker({
    position: path[path.length - 1],
    icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
    map: window.MAPINSTANCE
  });

  let routeLine = new window.AMap.Polyline({
    path: path,
    isOutline: true,
    outlineColor: "#ffeeee",
    borderWeight: 5,
    strokeWeight: 5,
    strokeColor: "#a606f7",
    lineJoin: "round"
  });

  routeLine.setMap(window.MAPINSTANCE);

  // 调整视野达到最佳显示区域
  window.MAPINSTANCE.setFitView([startMarker, endMarker, routeLine]);
}

// 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
// DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
function parseRouteToPath(route) {
  let path = [];
  for (let i = 0, l = route.steps.length; i < l; i++) {
    let step = route.steps[i];

    for (let j = 0, n = step.path.length; j < n; j++) {
      path.push(step.path[j]);
    }
  }
  return path;
}
